<template>
	<!-- 容器 -->
	<div ref="chartRef" style="width: 600px; height: 400px;"></div>
</template>

<script setup lang="ts">
    import { ref, onMounted, onBeforeUnmount } from 'vue'
    import * as echarts from 'echarts'
    import type { EChartsOption, ECharts } from 'echarts'

    /** 1. 图表 DOM 容器引用 */
    const chartRef = ref<HTMLDivElement | null>(null)

    /** 2. 图表实例 */
    let chartInstance: ECharts | null = null

    /** 3. 初始化函数 */
    const initChart = () => {
        if (chartRef.value) {
            chartInstance = echarts.init(chartRef.value)

            const option: EChartsOption = {
                title: {
                    text: '直接集成 ECharts'
                },
                tooltip: {},
                xAxis: {
                    type: 'category',
                    data: ['A', 'B', 'C', 'D', 'E']
                },
                yAxis: {
                    type: 'value'
                },
                series: [
                    {
                        name: '销量',
                        type: 'bar',
                        data: [5, 20, 36, 10, 10]
                    }
                ]
            }

            chartInstance.setOption(option)
        }
    }

    /** 4. 窗口大小变化时自适应 */
    const resizeChart = () => {
        chartInstance?.resize()
    }

    /** 5. 生命周期 */
    onMounted(() => {
        initChart()
        window.addEventListener('resize', resizeChart)
    })

    onBeforeUnmount(() => {
        window.removeEventListener('resize', resizeChart)
        chartInstance?.dispose()
    })
</script>

<style scoped>
	/* 可选：让图表容器自适应父级大小 */
	div {
		max-width: 100%;
	}
</style>
